package com.ecloud.gardenscenter.service.mqtt;

import com.ecloud.gardenscenter.constant.TopicConstant;
import com.ecloud.gardenscenter.mqtt.MqttTemplate;
import com.ecloud.gardenscenter.mqtt.constant.MqttMessageArrivedCall;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author Squbi
 */
@Component
public class MqttCallBackService implements MqttMessageArrivedCall {

    private static final Logger LOGGER = LoggerFactory.getLogger(MqttCallBackService.class);

    private void server(MqttTemplate template, MqttMessage message) {
        LOGGER.info("message from server : {}", message);
        try {
            //todo
            template.subscribe(new String(message.getPayload()), 2);
        } catch (MqttException e) {
            LOGGER.error("mqtt subscribe err", e);
        }
    }

    private void other(MqttTemplate template, String topic, MqttMessage message) {
        LOGGER.info("message from `{}` topic : {}", topic, message);
    }

    @Override
    public void exec(MqttTemplate template, String topic, MqttMessage message) {
        if (topic.equals(TopicConstant.SERVER)) {
            server(template, message);
        } else {
            other(template, topic, message);
        }
    }
}
